<template>
  <view class="container" style="background: #fff; padding-top: 5px">
    <uni-section title="基础数据" type="line">
      <view class="example" style="padding: 10px">
        <uni-forms
          ref="baseForm"
          :model="formData"
          labelWidth="150rpx"
        >
          <uni-forms-item label="车牌号码" name="licensePlate" :required="true">
            <uni-easyinput
              type="text"
              v-model="formData.licensePlate"
              placeholder="请输入车牌号"
              :disabled="formData.status != 0"
              required
            />
          </uni-forms-item>
          <uni-forms-item label="联系电话" name="contactNumber" :required="true">
            <uni-easyinput
              type="text"
              v-model="formData.contactNumber"
              placeholder="请输入联系电话"
              :disabled="formData.status != 0"
              required
            />
          </uni-forms-item>
          <uni-forms-item label="选择门店" :required="true">
            <uni-data-select v-model="formData.storeId" :localdata="selectData.storeList"
                             required
                             :disabled="true">
            </uni-data-select>
          </uni-forms-item>
          <uni-forms-item label="选择仓库" :required="true">
            <uni-data-select v-model="formData.warehouseId" :localdata="selectData.warehouseList"
                             required
                             :disabled="formData.status != 0">
            </uni-data-select>
          </uni-forms-item>
          <uni-forms-item label="存储类型" :required="true">
            <uni-data-select
              v-model="formData.storageType"
              :localdata="selectData.storageTypeList"
              :disabled="formData.status != 0"
              required
            >
            </uni-data-select>
          </uni-forms-item>
        </uni-forms>
      </view>
    </uni-section>

    <uni-section title="轮胎数据" type="line">
      <view class="button-sp-area">
        <button class="mini-btn" type="warn" size="mini" @click="delDepositRecordsDetail"
                :disabled="formData.status != 0"
        >删除
        </button>
        <button class="mini-btn" type="primary" size="mini" @click="addDepositRecordsDetail"
                :disabled="formData.status != 0"
        >新增
        </button>
      </view>
      <uni-table
        ref="table"
        :loading="loading"
        border
        stripe
        type="selection"
        emptyText="暂无更多数据"
        @selection-change="selectionChange"
      >
        <uni-tr>
          <uni-th width="150" align="center">季节胎型</uni-th>
          <uni-th width="150" align="center">轮胎品牌</uni-th>
          <uni-th width="150" align="center">轮胎型号</uni-th>
          <uni-th align="center">存储数量</uni-th>
          <uni-th align="center">备注</uni-th>
        </uni-tr>
        <uni-tr v-for="(item, index) in formData.depositRecordsDetails" :key="index">
          <uni-td align="center">
            <uni-data-select
              :disabled="formData.status != 0"
              v-model="item.tireSeason"
              :localdata="selectData.tireSeasonList"
            ></uni-data-select>
          </uni-td>
          <uni-td align="center">
            <next-data-select
              :disabled="formData.status != 0"
              v-model="item.tireBrand"
              :options="selectData.tireBrandList"
              :filterable="true" />
          </uni-td>
          <uni-td align="center">
            <next-data-select
              :disabled="formData.status != 0"
              v-model="item.tireModel"
              :options="selectData.tireModelList"
              :filterable="true"  />
          </uni-td>
          <uni-td align="center">
            <uni-number-box :min="1" v-model="item.storageQuantity"
                            :disabled="formData.status != 0"
                            required />
          </uni-td>
          <uni-td align="center">
            <uni-easyinput v-model="item.notes"
                            :disabled="formData.status != 0"
                            required />
          </uni-td>
        </uni-tr>
        <view style="width: 100%;height: 200px">&nbsp;</view>
      </uni-table>
    </uni-section>
    <view style="width: 100%;height: 80px">&nbsp;</view>
    <view class="goods-carts"
          v-show="['0'].includes(`${formData.status}`)"
          style="z-index: 9999;">
      <uni-goods-nav
        :options="options"
        :fill="true"
        :button-group="buttonGroup"
        @buttonClick="submitForm"
      />
    </view>
  </view>
</template>

<script lang="ts">
  import { DictUtils } from '@/sheep/store/DictUtils';
  import { StoreApi } from '@/sheep/api/store';
  import { WarehouseApi } from '@/sheep/api/warehouse';
  import { DepositRecordsApi } from '@/sheep/api/depositrecords';

  export default {
    onLoad(options) {
      this.id = options.id; // 获取 URL 中传递的 id 参数
    },
    mounted() {
      this.initSelectData();
      this.query();
    },
    data() {
      return {
        id: undefined,
        selectData: {
          storeList: [],
          storageTypeList: [],
          warehouseList: [],
          tireSeasonList: [],
          tireBrandList: [],
          tireModelList: [],
        },
        formData: {
          id: undefined,
          storeId: uni.getStorageSync('storeId'),
          licensePlate: undefined,
          contactNumber: undefined,
          startDate: undefined,
          storageDays: undefined,
          expirationDate: undefined,
          storageType: '0',
          warehouseId: undefined,
          warehouseDetail: undefined,
          notes: undefined,
          status: 0,
          depositRecordsDetails: [],
        },
        loading: false,

        options: [],

        buttonGroup: [
          {
            text: '新增保存',
            backgroundColor: 'linear-gradient(90deg, #FE6035, #EF1224)',
            color: '#fff',
          },
        ],
      };
    },
    methods: {
      async submitForm() {
        //因为是复制新增，关联信息全部清空
        this.cleanJoinId();

        const {data,msg,code} = await DepositRecordsApi.createDepositRecords(this.formData);
        if(code!=0){
          return uni.showToast({
            title: msg,
            icon: 'none',
          });
        }
        uni.showToast({
          title: `新增成功`,
          icon: 'none',
        });
        uni.navigateTo({
          url:'/pages/depositrecords/depositrecords'
        });
      },
      // 多选
      selectionChange(e) {
        console.log(e.detail.index);
        this.selectedIndexs = e.detail.index;
      },
      addDepositRecordsDetail() {
        this.formData.depositRecordsDetails.push({
          tireSeason: '0',
          tireBrand: '0',
          tireModel: '0',
          notes: '',
          storageQuantity: 4,
        });
      },
      delDepositRecordsDetail() {
        if (this.selectedIndexs && this.selectedIndexs.length > 0) {
          // 逆序删除，避免下标错乱
          this.selectedIndexs
            .sort((a, b) => b - a)
            .forEach((index) => {
              this.formData.depositRecordsDetails.splice(index, 1); // 删除对应下标的对象元素
            });
        }
      },
      async initSelectData() {
        try {
          // 获取字典数据
          const dictDataPromises = [
            DictUtils.getDictData('tire_storage_type'),
            DictUtils.getDictData('tire_storage_season'),
            DictUtils.getDictData('tire_storage_brand'),
            DictUtils.getDictData('tire_storage_model')
          ];

          const [storageTypeList, tireSeasonList, tireBrandList, tireModelList] = await Promise.all(dictDataPromises);
          this.selectData.storageTypeList = storageTypeList;
          this.selectData.tireSeasonList = tireSeasonList;
          this.selectData.tireModelList = tireModelList;
          this.selectData.tireBrandList = tireBrandList;

          // 获取仓库和商店数据
          const storeResultPromise = StoreApi.getStorePage({});
          const warehouseResultPromise = WarehouseApi.getWarehousePage({});

          const [storeResult, warehouseResult] = await Promise.all([storeResultPromise, warehouseResultPromise]);

          this.selectData.storeList = await this.buildSelectData(storeResult?.data?.list || [], 'storeName');
          this.selectData.warehouseList = await this.buildSelectData(warehouseResult?.data?.list || [], 'warehouseName');
        } catch (error) {
          console.error("初始化选择数据时出错:", error);
          // 可以在这里添加一些用户友好的提示或错误处理逻辑
        }
      },
      async query() {
        if (!this.id) {
          return;
        }
        const { data:depositRecordsData } = await DepositRecordsApi.getDepositRecords(this.id);
        this.formData = depositRecordsData || {};

        const { data:depositRecordsDetailData} = await DepositRecordsApi.getDepositRecordsDetailListByTireDepositRecordsId(this.id);
        this.formData.depositRecordsDetails = depositRecordsDetailData || [];

        this.cleanJoinId();
      },
      async buildSelectData(list: any[], name: string) {
        return list.map(item => ({
          value: item['id'],
          text: item[name]
        }));
      },
      // 格式化时间
      formatDate(date: string) {
        const d = new Date(date);
        const pad = (num: number) => String(num).padStart(2, "0");

        return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
      },
      cleanJoinId(){
        //因为是复制新增，关联信息全部清空
        this.formData.id = 0;
        this.formData.status = 0;
        this.formData.startDate = null;
        this.formData.expirationDate = null;
        this.formData.depositRecordsDetails.forEach((item) => {
          item.id = null;
          item.tireDepositRecordsId = null;
          item.remainingQuantity = item.storageQuantity; //库存数量直接为存储数量
          item.notes = item.notes; //库存数量直接为存储数量

          const seasonDictData = DictUtils.getDictData('tire_storage_season');
          const foundItem = seasonDictData.find(({ value }) => value !== `${item.tireSeason}`);

          item.tireSeason = foundItem?.value ?? `${item.tireSeason}`;
        });
      }
    },
  };
</script>

<style>
  .mini-btn {
    margin-left: 10rpx;
  }

  .example-body {
    padding: 0;
    /* #ifndef APP-NVUE */
    display: block;
    /* #endif */
  }

  .goods-carts {
    /* #ifndef APP-NVUE */
    display: flex;
    /* #endif */
    flex-direction: column;
    position: fixed;
    left: 0;
    right: 0;
    /* #ifdef H5 */
    left: var(--window-left);
    right: var(--window-right);
    /* #endif */
    bottom: 0;
  }
</style>
